<template>
	<view class="home-wrap u-m-b-20">
		<base-nav-bar :backIconColor="'#333'" :isBack="true" :background="{'background':'#fff'}">
			<text
				slot="content"
				style="color: #333; width: 100%; text-align: center;padding-left: 20rpx;"
			>
				新增课程
			</text>
		</base-nav-bar>
		<view class="content-box u-p-20 u-m-t-30 u-m-l-40 u-m-r-40">
			<!-- grid商家功能模块 -->
			<view class="u-flex u-flex-items-center u-flex-start u-flex-wrap">
				<u--form :model="form" ref="uForm" :labelPosition="'top'" style="width: 100%;" :labelStyle="{'margin-botttom':'10rpx'}">
					<u-form-item label="课程名称" prop="name" labelWidth="120">
						<u-input v-model="form.name" placeholder="请输入课程名称"/>
					</u-form-item>
					<u-form-item label="课程介绍" prop="description" labelWidth="120">
						<u--textarea v-model="form.description" placeholder="请输入课程介绍" ></u--textarea>
					</u-form-item>
					<u-form-item label="课程类型" prop="type" labelWidth="120">
						<view class="u-flex u-flex-wrap">
							<view class="u-page__tag-item" v-for="(item, index) in leixingList" :key="index">
								<u-tag :text="item.name" :plain="!item.checked" type="success" :name="index"
								       size="large"
								       @click.stop="radioClick($event,item,index)">
								</u-tag>
							</view>
						</view>
					</u-form-item>
					<u-form-item label="课时数量(小时)" prop="sum" labelWidth="120">
						<u-number-box v-model="form.sum" @change="valChange"></u-number-box>
					</u-form-item>
					<u-form-item label="课程价格(元)" prop="price" labelWidth="120">
						<u-input v-model="form.price" placeholder="请输入课程价格"/>
					</u-form-item>
					<u-form-item label="选择上课老师" labelWidth="120"
					             prop="merchant_teacher_id"
					             ref="item1"
					             @click.stop="openTeacher()">
						<u-input
							v-model="form.merchant_teacher"
							placeholder="请选择上课老师"
							suffixIcon="arrow-right"
							suffixIconStyle="color: #909399"
							readonly
						></u-input>
					</u-form-item>
<!--					<u-form-item label="授课老师手机号" prop="phone" labelWidth="120">-->
<!--						<u-input v-model="form.phone" placeholder="请输入授课老师手机号"/>-->
<!--					</u-form-item>-->
<!--					<u-form-item label="课程标签" prop="course_label_id" labelWidth="120">-->
<!--						<view class="u-flex u-flex-wrap">-->
<!--							<view class="u-page__tag-item" v-for="(item, index) in tagsList" :key="index">-->
<!--								<u-tag :text="item.name" :plain="!item.checked" type="success" :name="index"-->
<!--								       size="large"-->
<!--								       @click.stop="checkboxClick($event,item,index)">-->
<!--								</u-tag>-->
<!--							</view>-->
<!--						</view>-->
<!--					</u-form-item>-->
					<u-form-item label="选择课程分类" labelWidth="120"
					             prop="course_category_id"
					             ref="item2"
					             @click.stop="openClass()">
						<u-input
							v-model="form.course_category"
							placeholder="请选择课程分类"
							suffixIcon="arrow-right"
							suffixIconStyle="color: #909399"
							readonly
						></u-input>
					</u-form-item>
					<u-form-item label="请上传课程图片" prop="name" labelWidth="120">
						<u-upload
							:fileList="courseImages"
							@afterRead="afterRead"
							@delete="deletePic"
							name="Images"
							multiple
							:previewFullImage="true"
						></u-upload>
					</u-form-item>
					<u-form-item label="开班起止时间" labelWidth="120" prop="begintime" v-if="form.type=='1'">
						<view :style="{'background':'#fff','border-radius': '6px','border': '1px solid','border-color':'#ccc!important'}" class="u-flex u-flex-between u-flex-items-center u-p-l-10 u-p-r-10">
							<u-icon :color="'#000'" :size="16" name="clock"></u-icon>
							<view @click="openBeginTime()">
								<u-input v-model="form.str_time" :border="false" inputAlign="center" placeholder="开始时间" readonly/>
							</view>
							<view style="width: 2%; height: 4rpx;background: #000;"></view>
							<view @click="openEndTime()">
								<u-input v-model="form.end_time" :border="false" inputAlign="center" placeholder="结束时间" readonly/>
							</view>
						
						</view>
					</u-form-item>
				</u--form>
				<view class="submit-btn" @click="submit">提交</view>
			</view>
		</view>
		<u-picker :close-on-click-overlay="true" :show="showTeacher" :columns="teacherList" :title="'选择老师'" key-name="name" @confirm="chooseTeacher($event)" @cancel="closeTeacher()"></u-picker>
		<u-picker :close-on-click-overlay="true" :show="showClass" :columns="typeList" :title="'选择课程分类'" key-name="name" @confirm="chooseClass($event)" @cancel="closeClass()"></u-picker>
		<u-datetime-picker
			v-model="value1"
			:show="showBeginTime"
			mode="date"
			title="选择开始时间"
			@cancel="closeBeginTime"
			@confirm="chooseBeginTime"
		></u-datetime-picker>
		<u-datetime-picker
			v-model="value2"
			:show="showEndTime"
			mode="date"
			title="选择结束时间"
			@cancel="closeEndTime"
			@confirm="chooseEndTime"
		></u-datetime-picker>
	</view>
</template>

<script>

import { mapGetters } from 'vuex';
import { HTTP_IMG_URL } from '../../config/app.js'
import BaseNavBar from "../../components/BaseNavBar.vue";

export default {
	components: {
		BaseNavBar
	},
	data() {
		return {
			showTeacher:false,
			showClass:false,
			courseImages:[],
			showBeginTime : false,
			showEndTime   : false,
			value1        : Number(new Date()),
			value2        : Number(new Date()),
			endTime:'',
			beginTime:'',
			form: {
				name: '',
				sum:0,
				description:'',
				price:'',
				image:'',
				merchant_teacher_id:'',
				merchant_teacher:'',
				course_category_id:'',
				course_category:'',
				course_label_id:'',
				course_label_id_arr:[],
				str_time  : '',
				end_time    : '',
			},
			courseId:'',
			typeList:[],
			tagsList:[],
			teacherList:[],
			rules: {
				name: [
					{
						required: true,
						message: '请输入名称',
						trigger: ['blur', 'change']
					}
				]
			},
			leixingList: [{id:'1',name:'训练营',checked:false}, {id:'0',name:'普通课程',checked:false}],
		};
	},
	computed: {
		...mapGetters(['isLogin','userInfo']),
		
	},
	onPullDownRefresh() {
	
	},
	
	onShow() {
	
	},
	onHide() {
	},
	onLoad(options) {
		this.getTagsList();
		this.getTeacherList();
		console.log("====options",options)
		if(options&&options.id){
			this.courseId = options.id
			setTimeout(()=>{
				this.getCourseDetails()
			},500)
		}
	},
	onReady() {
		//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		this.$refs.uForm.setRules(this.rules)
	},
	methods: {
		openBeginTime() {
			this.showBeginTime = true;
		},
		openEndTime() {
			this.showEndTime = true;
		},
		chooseBeginTime(e) {
			this.showBeginTime = false;
			console.log("=== this.showBeginTime = false;", e)
			this.beginTime      = e.value;
			this.form.str_time = this.formatTimestamp(this.beginTime);
		},
		closeBeginTime() {
			this.showBeginTime = false;
		},
		chooseEndTime(e) {
			this.showEndTime = false;
			console.log("=== this.showBeginTime = false;", e)
			this.endTime      = e.value;
			this.form.end_time = this.formatTimestamp(this.endTime);
		},
		closeEndTime() {
			this.showEndTime = false;
		},
		formatTimestamp(timestamp) {
			const date    = new Date(timestamp);
			const year    = String(date.getFullYear());
			const month   = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1，并且保证两位数
			const day     = String(date.getDate()).padStart(2, '0'); // 保证两位数
			return `${year}-${month}-${day}`;
		},
		valChange(e){
			this.form.hours = e
		},
		checkboxClick(name,item,index) {
			this.tagsList.map((item2,index2)=>{if(index2!=index){item2.checked = false}})
			this.tagsList[index].checked = !this.tagsList[index].checked;
			this.tagsList.splice(index,1,item);
		},
		radioClick(name,item,index) {
			this.form.type = item.id;
			this.leixingList.map((item2,index2)=>{if(index2!=index){item2.checked = false}})
			this.leixingList[index].checked = !this.leixingList[index].checked;
			this.leixingList.splice(index,1,item);
		},
		openTeacher(){
			this.showTeacher = true;
			console.log("====this.showTeacher",this.teacherList)
		},
		openClass(){
			let course_label_id = '';
			// this.tagsList.forEach(item=>{
			// 	if(item.checked){
			// 		course_label_id =item.id;
			// 	}
			// })
			// if(course_label_id==''){
			// 	uni.$u.toast('请先选择课程标签');
			// 	return
			// }
			this.getTypeList();
			this.showClass = true;
			console.log("====this.showClass",this.typeList)
		},
		closeTeacher(){
			this.showTeacher = false;
		},
		closeClass(){
			this.showClass = false;
		},
		chooseTeacher(e){
			this.showTeacher = false;
			console.log("222---e",e);
			this.form.merchant_teacher_id = e.value[0].id
			this.form.merchant_teacher = e.value[0].name
		},
		chooseClass(e){
			this.showClass = false;
			this.form.course_category_id = e.value[0].id
			this.form.course_category = e.value[0].name
			console.log("333---e",e)
		},
		HTTP_IMG_URL() {
			return HTTP_IMG_URL
		},
		// 路由跳转
		jump(path, parmas) {
			uni.navigateTo({
				url: path,
				query: parmas
			});
		},
		submit() {
			this.form.course_label_id_arr = [];
			// this.tagsList.forEach(item=>{
			// 	if(item.checked){
			// 		this.form.course_label_id_arr.push(item.id)
			// 	}
			// })
      if(this.form.type==='0'){
          this.form.str_time = '';
          this.form.end_time = '';
      }
			let imageArr = [];
			if(this.courseImages.length>0){
				this.courseImages.forEach(item=>{
					imageArr.push(item.url)
				})
			}
			this.$refs.uForm.validate().then(res => {
				let fromData = {
					...this.form,
					images:imageArr.join(','),
					image:imageArr.join(','),
					// course_label_id:this.form.course_label_id_arr.join(','),
				}
				if(this.courseId){
					fromData = {
						...fromData,
						id:this.courseId
					}
					this.$Api.merchant.courseEditPost(fromData).then(res=>{
						uni.$u.toast('修改成功')
						setTimeout(()=>{
							uni.navigateBack({
								delta: 1
							})
						},500)
					}).catch(err=>{
						console.log(e)
					})
				}else{
					this.$Api.merchant.courseAdd(fromData).then(res=>{
						uni.$u.toast('新增成功')
						setTimeout(()=>{
							uni.navigateBack({
								delta: 1
							})
						},500)
					}).catch(err=>{
						console.log(e)
					})
				}
			}).catch(errors => {
				uni.$u.toast('校验失败')
			})
		},
		// 删除图片
		deletePic(event) {
			this[`course${event.name}`].splice(event.index, 1)
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			let fileListLen = this[`course${event.name}`].length
			for (let i = 0; i < lists.length; i++) {
				const result = await this.$uploadFilePromise(lists[i].url)
				this[`course${event.name}`].splice(fileListLen, 1, {
					status: 'success',
					message: '',
					url: result.fullurl
				})
				fileListLen++
			}
			console.log("===this.tagsList",this.tagsList);
		},
		getTeacherList(){
			var that = this;
			this.teacherList = [];
			that.$Api.merchant.merchantTeacherListAl().then(res=>{
				this.teacherList.push(res.data);
			}).catch(err=>{
				console.log(e)
			})
		},
		getTagsList(){
			var that = this;
			that.$Api.merchant.courseLabel().then(res=>{
				console.log("====res",res)
				this.tagsList = res.data;
				this.tagsList.map((item,index)=>{
					item.checked = false
				})
			}).catch(err=>{
				console.log(e)
			})
		},
		getTypeList(course_label_id){
			var that = this;
			that.typeList = [];
			that.$Api.merchant.courseCategory().then(res=>{
				that.typeList.push(res.data);
				if(that.form.course_category_id){
					console.log("===that.typeList",that.typeList[0])
					that.typeList[0].forEach((item2,index2)=>{
						if(item2.id == that.form.course_category_id){
							that.form.course_category = item2.name
						}
					})
				}
			}).catch(err=>{
				console.log(e)
			})
		},
		getCourseDetails(){
			let that = this;
			that.$Api.merchant.courseEdit({id:this.courseId}).then(res=>{
				this.form = res.data;
				this.courseImages = [];
				let imageArr = that.form.image.split(',');
				imageArr.forEach(item=>{
					let obj = {
						url: item
					}
					that.courseImages.push(obj)
				})
				// that.tagsList.forEach((item2,index2)=>{
				// 	if(item2.id == that.form.course_label_id){
				// 		item2.checked = true
				// 	}
				// })
        that.leixingList.forEach((item2,index2)=>{
					if(item2.id == that.form.type){
						item2.checked = true
					}
				})

				that.getTypeList();
				that.teacherList[0].forEach((item2,index2)=>{
					if(item2.id == that.form.merchant_teacher_id){
						that.form.merchant_teacher = item2.name
					}
				})
				// console.log("======tagsList",that.tagsList)
			}).catch(err=>{
				console.log(e)
			})
		}
	}
};
</script>

<style lang="scss" scoped>
/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
.home-wrap {
	min-height: 100vh;
	background: #F6F6F8;
	position: relative;
}
.kehu-item {
	border-radius: 20rpx;
	width: 100%;
	.swipers{
		width: 100%;
	}
}
.nickname{
	font-size: 34rpx;
	font-weight: bold;
}
.content-box{
	background: #FFFFFF;
	border-radius: 30rpx;
	min-height: 80vh;
	.pay-item{
		width: 25%;
	}
}
::v-deep .u-form{
	width: 100%;
}
.images-content{
	width: 100%;
	height: 300rpx;
	display: flex;
	border:1rpx solid #eee;
}
.submit-btn{
	margin-top: 20rpx;
	width: 100%;
	height: 84rpx;
	background: linear-gradient( #30AA4D 0%, #20CE83 100%);
	box-shadow: 0px 2px 4px 0px rgba(48,170,77,0.1);
	border-radius: 8px;
	display: flex;
	justify-content: center;
	align-items: center;
	color: #fff;
	font-size: 28rpx;
}
.u-page__tag-item {
	margin-right: 20px;
	margin-top: 20rpx;
	&:nth-of-type(1) {
		margin-top: 0rpx;
	}
	&:nth-of-type(2) {
		margin-top: 0rpx;
	}
	&:nth-of-type(3) {
		margin-top: 0rpx;
	}
}
::v-deep .u-tag--success--plain{
	background: #F6F6F8 !important;
	border-color: #EDEDED !important;
	color: #C7C7C7 !important;
}
::v-deep .u-tag__text--success--plain{
	color: #C7C7C7 !important;
}
::v-deep .u-tag--success{
	background: linear-gradient(#30AA4D 0%, #20CE83 100%);
	box-shadow: 0px 2px 4px 0px rgba(48,170,77,0.1);
	border-width: 1px;
	border-color: #30AA4D;
}
.teShu-item{
	::v-deep .u-form-item__body{
		flex-direction: row!important;
	}
}
</style>
